package com.panshi.repast.Http;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;

import com.panshi.repast.String.AppdataString;

/**
 * 网络连接基类
 * 
 * @author Administrator
 * 
 */
@SuppressLint("DefaultLocale")
public class HttpClientExecutor {

	private static final int TIMEOUT = 10000;
	private static final int TIMEOUT_SOCKET = 10000;

	// 代理wap10.0.0.172
	public static final int TYPE_CM_CU_WAP = 0;
	// 代理wap 10.0.0.200
	public static final int TYPE_CT_WAP = 1;
	// 判断是否是wifi
	public static final int TYPE_OTHER_NET = 2;
	public static Uri PREFERRED_APN_URI = Uri
			.parse("content://telephony/carriers/preferapn");

	/************ Singleton ***********/
	private static HttpClientExecutor instance = new HttpClientExecutor();

	private HttpClientExecutor() {

	}

	public static HttpClientExecutor getInstance() {
		return instance;
	}

	private HttpClient newHttpClient() {
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		HttpProtocolParams.setUseExpectContinue(params, true);

		// 设置超时时间
		ConnManagerParams.setTimeout(params, 60000);
		HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET);

		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schReg.register(new Scheme("https",
				SSLSocketFactory.getSocketFactory(), 443));

		// 链接管理器ClientConnectionManager
		ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(
				params, schReg);

		switch (checkUserProxy()) {
		case TYPE_CM_CU_WAP: {
			// 判断是否是联通GPRS，如果是使用代理
			HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
			params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		}
			break;
		case TYPE_CT_WAP: {
			// 判断是否是 电信GPRS，如果是使用代理
			HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
			params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		}
			break;
		}

		HttpClient mHttpClient = new DefaultHttpClient(connectionManager,
				params);
		return mHttpClient;
	}

	/***
	 * 连接网络，判断状态
	 * 
	 * */
	@SuppressLint("DefaultLocale")
	public static int checkUserProxy() {
		try {
			final ConnectivityManager connectivityManager = (ConnectivityManager) AppdataString.sMainContext
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			final NetworkInfo networkInfo = connectivityManager
					.getActiveNetworkInfo();
			if (networkInfo != null && networkInfo.isAvailable()) {
				int netType = networkInfo.getType();
				if (netType == ConnectivityManager.TYPE_MOBILE) {
					final Cursor c = AppdataString.sMainContext
							.getContentResolver().query(PREFERRED_APN_URI,
									null, null, null, null);
					if (c != null) {
						c.moveToFirst();
						final String user = c.getString(c
								.getColumnIndex("user"));
						if (user != null && user.startsWith("ctwap")) {
							return TYPE_CT_WAP;
						}
						c.close();
					}

					String netMode = networkInfo.getExtraInfo();
					if (netMode != null) {
						netMode = netMode.toLowerCase();
						if (netMode.equals("cmwap") || netMode.equals("3gwap")
								|| netMode.equals("uniwap")) {
							return TYPE_CM_CU_WAP;
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return TYPE_OTHER_NET;
		}
		return TYPE_OTHER_NET;
	}

	/**
	 * 连接网络post方式，直连
	 * 
	 * @param destUrl
	 * @return httpPost
	 */
	public HttpPost newHttpPost(String destUrl) throws Exception {
		HttpPost httpPost = new HttpPost(destUrl);
		httpPost.setHeader("accept", "*/*");
		return httpPost;
	}

	/**
	 * 连接网络get方式，直连
	 * 
	 * @param destUrl
	 * @return httpGet
	 */
	public HttpGet newHttpGet(String destUrl) throws Exception {
		HttpGet httpGet = new HttpGet(destUrl);
		httpGet.setHeader("accept", "*/*");
		return httpGet;
	}

	/**
	 * post方式连接，传参
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public byte[] executePost(String url, List<NameValuePair> params) {
		byte[] resData = null;
		HttpPost httpPost = null;
		try {
			if (!checkUrl(url))
				return null;
			httpPost = this.newHttpPost(url);

			// 设置post编码
			if (params != null && params.size() > 0) {
				httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			}

			// 连接网络获取HttpResponse
			HttpResponse httpResponse = newHttpClient().execute(httpPost);
			// 状态是否成功
			StatusLine statusLine = null;
			if (httpResponse == null
					|| (statusLine = httpResponse.getStatusLine()) == null)
				return null;

			int responseCode = statusLine.getStatusCode();

			if (responseCode == HttpStatus.SC_OK) {
				resData = EntityUtils.toByteArray(httpResponse.getEntity());
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (httpPost != null) {
				httpPost.abort();
			}
		}
		return resData;
	}

	/**
	 * 连接网络get方式,传参
	 * 
	 * @param url
	 */
	public byte[] executeGet(String url) {
		byte[] data = null;
		try {
			if (!checkUrl(url))
				return null;
			URL path = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) path.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(50000);
			InputStream inStream = conn.getInputStream();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
			data = bos.toByteArray();
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	/**
	 * 获取HttpResponse实列
	 * 
	 * @param obj
	 */
	public HttpResponse getHttpResponse(HttpUriRequest request)
			throws Exception {
		HttpResponse httpResponse = newHttpClient().execute(request);
		return httpResponse;
	}

	/**
	 * 判断URL地址是否合法
	 * 
	 * @param url
	 * @return boolean
	 * 
	 */
	private static boolean checkUrl(String url) {
		return url.matches("^[a-zA-z]+://[^\\s]*$");
	}

}
